//
//  ZGLLeftMenuController.m
//  ZeegingLottery
//
//  Created by 蒂埃里 on 2018/3/29.
//  Copyright © 2018年 蒂埃里. All rights reserved.
//

#import "ZGLLeftMenuController.h"
#import "ZGLLoginStatusView.h"
#import "ZGLRegisterController.h"
#import "WKWebViewController.h"
#import "ZGLLotteryRecordController.h"
#import "ZGLRechargeController.h"
#import "ZGLExtractCashController.h"
#import "ZGLNameInfoController.h"
#import "ZGLBankCardInfoController.h"

//#import "ZGLSuccessCallBackVC.h" //

@interface ZGLLeftMenuController ()
{
    CGFloat offSet;
    CGFloat duration;
}

@property (strong, nonatomic)ZGLLoginStatusView *loginStatusView;
@property (nonatomic, copy) NSString *bankCardNum;
@property (nonatomic, copy) NSString *phoneNum;
@property (nonatomic, copy) NSString *balance; //可提现金额
@property (nonatomic, copy) NSString *realName;

@end

@implementation ZGLLeftMenuController

- (ZGLLoginStatusView *)loginStatusView
{
    if (!_loginStatusView) {
        _loginStatusView = [[ZGLLoginStatusView alloc]init];
        
    }
    
    return _loginStatusView;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = ViewBackgroundColor;
    
    [self.view addSubview:self.loginStatusView];
    [self setupUI];
    
    
    //即将显示的键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    //即将推出的键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}


- (void)setupUI
{
    [self.loginStatusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.centerY.equalTo(self.view);
//        make.top.equalTo(self.view).offset(50);
        make.size.mas_equalTo(CGSizeMake(UI_SCREEN_WIDTH*0.75, UI_SCREEN_HEIGHT*0.75));
    }];
    
    
    WS(weakself)
    //登录
    self.loginStatusView.loginButtonTouchBlock = ^(NSString *acount, NSString *password) {
        DLog(@"登录");
        
//        sZGLUserInfoModel.usercheck = YES;
        //已注册 登录按钮埋点
        [TalkingData trackEvent:ZGLLoginBtnEventID];
        
        [weakSelf loginWithAcount:acount Password:password];
        
    };
    
    //注册
    self.loginStatusView.registerButtonTouchBlock = ^(UIButton *registerBtn) {
        
        //未注册 注册按钮埋点
        [TalkingData trackEvent:ZGLUnsignInRegistBtnEventID];
        
        ZGLRegisterController *registVc = [[ZGLRegisterController alloc]init];
//        [weakSelf cw_presentViewController:registVc];
        [weakSelf cw_pushViewController:registVc drewerHiddenDuration:0.01];
        
    };

    
    self.loginStatusView.chargeButtonTouchBlock = ^{
        
        DLog(@"充值");
        
        [TalkingData trackEvent:ZGLChargeBtnEventID];
        
        [weakSelf goToChargeMoney];
    };
    
    self.loginStatusView.tiXianButttonTouchBlock = ^{
        
        DLog(@"提现");
        [TalkingData trackEvent:ZGLExtractBtnEventID];
        
//        ZGLSuccessCallBackVC *callbackVC = [[ZGLSuccessCallBackVC alloc]init];
//        [callbackVC initWithCallBackStatus:ZGLSuccessCallBackExtractCash Status:ZGLStatusFail];
////        callbackVC.status = 1;
//        callbackVC.statusMessageLabel.text = @"恭喜你，提现成功！";
////        callbackVC.supplyMessageLabel.text = @"订单正在送往投注站";
//        callbackVC.successTitle = @"成功";
//        callbackVC.subMessageLabel.text = @"预计到账时间：2018年11月27日 23:59";
//        callbackVC.businessDetailLablel.text = @"支付宝支付";
//        callbackVC.Amount.text = [NSString stringWithFormat:@"￥%@",@"100.00"];
//        ZGLNameInfoController *nameVC = [[ZGLNameInfoController alloc]initWithNibName:@"ZGLNameInfoController" bundle:nil];
//        [weakSelf cw_pushViewController:nameVC drewerHiddenDuration:0.01];
        
        BOOL is_realName = [sZGLUserInfoModel.is_real boolValue];
        BOOL is_realBank = [sZGLUserInfoModel.is_bank boolValue];

        if (!is_realName) {
            DLog(@"未实名认证");
            ZGLNameInfoController *nameVC = [[ZGLNameInfoController alloc]initWithNibName:@"ZGLNameInfoController" bundle:nil];
            [weakSelf cw_pushViewController:nameVC drewerHiddenDuration:0.01];

        }else if (!is_realBank){
            DLog(@"未绑定银行卡");
            ZGLBankCardInfoController *bankInfoVc = [[ZGLBankCardInfoController alloc]initWithNibName:@"ZGLBankCardInfoController" bundle:nil];
            bankInfoVc.realNameString = weakSelf.realName;
            [weakSelf cw_pushViewController:bankInfoVc drewerHiddenDuration:0.01];

        }else{
            
            //直接提现
            ZGLExtractCashController *extractVc = [[ZGLExtractCashController alloc]init];
            extractVc.isSlide = YES;
            [weakSelf cw_pushViewController:extractVc drewerHiddenDuration:0.01];
        }

    };
    
    self.loginStatusView.aboutUsCellTouhBlock = ^{
        
        DLog(@"关于我们");
        [TalkingData trackEvent:ZGLAboutUsBtnEventID];
        
        WKWebViewController *aboutUsVc = [[WKWebViewController alloc]init];
        aboutUsVc.isNavHidden = YES;
        //@"https://www.baidu.com/"
        NSString *aboutUsStr = @"http://betcat.zeeging.com/index.php/Info/aboutUs";
        [aboutUsVc loadWebURLSring:aboutUsStr];
        [weakSelf cw_pushViewController:aboutUsVc drewerHiddenDuration:0.01];
        
    };
    
    self.loginStatusView.gouCaiJiLuBtnTouchBlock = ^{
        
        [TalkingData trackEvent:ZGLLotteryRecordBtnEventID];
        
        ZGLLotteryRecordController *recordVC = [[ZGLLotteryRecordController alloc]init];
        [weakSelf cw_pushViewController:recordVC drewerHiddenDuration:0.01];
    };
    
    self.loginStatusView.loginOutButtonTouchBlock = ^{
        
        //退出登录埋点
        [TalkingData trackEvent:ZGLLoginOutBtnEventID];
        [weakSelf loginOut];
    };
    
}

//修改状态栏字体颜色
- (void)viewWillAppear:(BOOL)animated
{
//    [super viewWillAppear:animated];
    
    [TalkingData trackPageBegin:@"左抽屉界面"];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    BOOL isLogin = sZGLUserInfoModel.usercheck;
    if (isLogin) {
        
        [self UpdatePersonalInformation];
        
        WS(weakself)
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [weakSelf getExtractCashInfo];
        });
    }
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void)viewWillDisappear:(BOOL)animated
{
//    [super viewWillDisappear:animated];
    
    //埋点
    [TalkingData trackPageEnd:@"左抽屉界面"];
}

- (void)dealloc {
    DLog(@"%s",__func__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - meoth

////获取提现信息
- (void)getExtractCashInfo
{
    WS(weakself)
    [sZGLHTTPRequestManager getBankCardInfoWithSuccess:^(id responsedata) {
        
        weakSelf.realName = responsedata[@"real_name"];
        
    } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {
        
        DLog(@"获取提现信息失败");
    }];
}

//更新个人信息
- (void)UpdatePersonalInformation
{
    if (sZGLUserInfoModel.usercheck) {
        
        [sZGLHTTPRequestManager UpdatePersonalInformationWithSuccess:^(id responsedata) {
            
            ZGLUserInfoModel *model = [ZGLUserInfoModel mj_objectWithKeyValues:responsedata];
            [sZGLUserInfoModel setLoginSuccessedWithUserInfo:model];
            DLog(@"更新后--%@",sZGLUserInfoModel.balance);
            
        } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {
            
            DLog("更新失败");
            
        }];
    }
}

- (void)goToChargeMoney
{
    DLog(@"充值");
    
    ZGLRechargeController *rechangeVC = [[ZGLRechargeController alloc]init];
    [self cw_pushViewController:rechangeVC drewerHiddenDuration:0.01];
    
}

- (void)loginOut
{
    [EasyAlertView alertViewWithPart:^EasyAlertPart *{

        return [EasyAlertPart shared].setTitle(@"退出登录").setSubtitle(@"你确定要退出吗？").setAlertType(AlertViewTypeSystemAlert);

    } config:^EasyAlertConfig *{

        UIColor *tintC = [UIColor groupTableViewBackgroundColor];
        return [EasyAlertConfig shared].settwoItemHorizontal(YES).setAnimationType(AlertAnimationTypeFade).setTintColor(tintC).setBgViewEvent(NO).setSubtitleTextAligment(NSTextAlignmentLeft).setEffectType(AlertBgEffectTypeAlphaCover);

    } buttonArray:^NSArray<NSString *> *{

        return @[@"确定",@"取消"];

    } callback:^(EasyAlertView *showview, long index) {

        if (index == 0) {
            DLog(@"退出登录");
            
            [TalkingData trackEvent:ZGLLoginOutBtnEventID label:@"确定"];
            [sZGLUserInfoModel setLoginOutWithUserInfo];
        }else if (index == 1){
            
            [TalkingData trackEvent:ZGLLoginOutBtnEventID label:@"取消"];
        }

    }];
    
}

//调用登录接口
- (void)loginWithAcount:(NSString *)acount Password:(NSString *)password
{
    if (acount.length <= 0) {
        DLog(@"账号不能为空");
        
        [EasyTextView showInfoText:@"账号不能为空"];
        
    }else if (password.length <= 0){
        DLog(@"密码不能为空");
        
        [EasyTextView showInfoText:@"密码不能为空"];
        
    }else{
        
        NSString *Password = [PublicMethod MD5ForUpper32Bate:password];
        NSString *deviceName = [PublicMethod currentDeviceName];
        NSString *deviceModel = [PublicMethod currentDeviceModel];
        
        //登录请求
        [sZGLHTTPRequestManager loginWithMobilPhone:acount Password:Password LoginType:@"password_login" DeviceName:deviceName DeviceModel:deviceModel Success:^(id responseData) {
            
            NSString *code = responseData[@"code"];
            NSString *message = responseData[@"message"];
            if ([code integerValue] == 1) {
                DLog(@"登录成功");
                NSDictionary *data = responseData[@"data"];
                
                //登录埋点
//                [TalkingData onLogin:acount type:TDAccountTypeOriginalAcount name:@""];
                
                ZGLUserInfoModel *model = [ZGLUserInfoModel mj_objectWithKeyValues:data];
                [sZGLUserInfoModel setLoginSuccessedWithUserInfo:model];
                
                [EasyTextView showSuccessText:@"登录成功"];
                
                //请求支付权限状态
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [self getPaymentList];
                });
                
                
            }else if ([code integerValue] == 0 && [message isEqualToString:@"账号密码错误"]){
                DLog(@"账号密码错误");
                
                [EasyTextView showErrorText:@"登录失败，请核对账号"];
                
            }
            
        } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {
            DLog(@"登录失败");
            
            [EasyTextView showErrorText:@"登录失败，请重试"];
            
        }];
    }
}

//获取支付方式列表
- (void)getPaymentList
{
    [sZGLHTTPRequestManager getPaylistWithSuccess:^(id responsedata) {
        
        //        NSDictionary *data = responsedata[@"data"];
        DLog(@"paymentList-%@",responsedata);
        //        self.paymentList = responsedata;
        NSDictionary *paymentList = responsedata;
        //储存支付支持状态
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        NSString *fileName = [path stringByAppendingPathComponent:@"Paylist.plist"];
        //        [self.paymentList writeToFile:fileName atomically:YES];
        [paymentList writeToFile:fileName atomically:YES];
        
    } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {
        
    }];
}


#pragma mark - notification meth

- (void)keyboardWillShow:(NSNotification *)notifi
{
    
    NSDictionary *dict = notifi.userInfo;
    CGRect rect = [dict[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    duration = [[dict objectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];
    CGFloat keybH = rect.size.height;
    CGRect registerBtn = self.loginStatusView.registerBtn.frame;
    CGFloat registerBtnMaxH = CGRectGetMaxY(registerBtn);
    offSet = (registerBtnMaxH+keybH)-UI_SCREEN_HEIGHT;
    
    [self.loginStatusView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.centerY.equalTo(self.view).offset(-130);
        make.size.mas_equalTo(CGSizeMake(UI_SCREEN_WIDTH*0.75, UI_SCREEN_HEIGHT*0.75));
    }];
    
    [UIView animateWithDuration:duration animations:^{
        
        [self.view layoutIfNeeded];
        
    }];

    
}

- (void)keyboardWillHide:(NSNotification *)notifi
{

    [self.loginStatusView mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view);
        make.centerY.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(UI_SCREEN_WIDTH*0.75, UI_SCREEN_HEIGHT*0.75));
    }];
    
    [UIView animateWithDuration:1 animations:^{
        
        [self.view layoutIfNeeded];
    }];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
